@file:OptIn(ExperimentalMaterial3Api::class)

package com.auto.qinglong.ui.screens

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import com.auto.base.ui.HandleUiEvent
import com.auto.qinglong.ui.viewmodel.TaskLogViewModel

@Composable
fun TaskLogScreen(navController: NavHostController, taskId: String?, back: () -> Unit = {}) {
    val viewModel: TaskLogViewModel = hiltViewModel()
    HandleUiEvent(viewModel, navController)
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val scrollState = rememberScrollState()
    LaunchedEffect(taskId) {
        taskId?.let { viewModel.checkLog(it) }
    }
    // ✅ 监听 ViewModel 发出的滚动事件
    LaunchedEffect(Unit) {
        viewModel.scrollToBottomEvent.collect {
            scrollState.animateScrollTo(scrollState.maxValue)
        }
    }

    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(
                title = {
                    Text("日志")
                }, navigationIcon = {
                    IconButton(onClick = {
                        back()
                    }) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                }, colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.primary,
                )
            )
        }) {
        Column(
            Modifier
                .padding(it)
                .padding(horizontal = 20.dp, vertical = 5.dp)
                .verticalScroll(scrollState),
        ) {
            Text(uiState.logStr, style = MaterialTheme.typography.bodySmall)
        }
    }
}